package com.stu.manager.studentscoremanagersys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stu.manager.studentscoremanagersys.dto.JWTManagerDTO;
import com.stu.manager.studentscoremanagersys.Utils.JWTUtil;
import com.stu.manager.studentscoremanagersys.mapper.ManagerMapper;
import com.stu.manager.studentscoremanagersys.pojo.Manager;
import com.stu.manager.studentscoremanagersys.req.LoginReq;
import com.stu.manager.studentscoremanagersys.res.Result;
import com.stu.manager.studentscoremanagersys.service.ManagerService;
import com.stu.manager.studentscoremanagersys.vo.JWTManagerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ManagerServiceImpl implements ManagerService {
    @Autowired
    ManagerMapper managerMapper;

     public Result login(LoginReq loginReq){
         LambdaQueryWrapper<Manager> lambdaQueryWrapper = new LambdaQueryWrapper<>();
         lambdaQueryWrapper.eq(Manager::getUserName,loginReq.getUsername()).eq(Manager::getPwd,loginReq.getPwd());
         Manager manager =  managerMapper.selectOne(lambdaQueryWrapper);
         log.info("result:{}", JSON.toJSONString(manager));
         if (manager==null){
             return Result.buildFailure("用户名或密码不正确");
         }
         //生成token
         JWTManagerVo vo =  genernateToken(manager);
//         log.info("result:{}",JSON.toJSONString(vo));

         return Result.buildScuess(vo);
     }

    private JWTManagerVo genernateToken(Manager manager) {
        JWTManagerDTO jwtManagerDTO = new JWTManagerDTO();
        BeanUtils.copyProperties(manager,jwtManagerDTO);
        //返回前端token+用户信息
        JWTManagerVo vo = new JWTManagerVo();
        BeanUtils.copyProperties(jwtManagerDTO,vo);
        String token = JWTUtil.getToken(jwtManagerDTO);
        vo.setToken(token);
        return vo;
    }
}
